CURRENT_PAGE = 1;//当前页数
PAGE_COUNT = 10;//取多少条数据
CURRENT_GOODS_ID = null;
SELECTED_GOODS_ARY = [];
GOODSLIST = [];
SAVEING_FLAG = false;
TEMPLATE = null;
TEMPDATA = null;
GOODSNAME = null;
PRICE_TITLE = '设置藏品起拍价格';
CATID = null;
$(function(){
	loadGoods();
	lh.scrollBottom(loadGoods);
	$("#selectNum").text(0);
	initData();
});

//TODO 1.检查是否有资金操作，有则提示输入支付密码、2批发城藏品，则设置代理价格，批发价格等

function initData(){
	var comeFrom = localStorage.getItem("comeFrom");
    if(comeFrom == 5){
    	PRICE_TITLE = '设置商品批发价格';
    }
    if(comeFrom == 1){//专场已经存在商品
    	var professionId = localStorage.getItem("professionId");
    	loadAuctionProfessionGoods(professionId);
    }
    if(comeFrom == 2){//即时拍已经存在商品
    	var auctionQuickId = localStorage.getItem("auctionQuickId");
    	loadAuctionQuickGoods(auctionQuickId);
    }
    if(comeFrom == 3){//微拍已经存在商品
    	loadAuctionMicroGoods();
    }
    
}

function loadAuctionMicroGoods(){
	var obj = {forAuction:1,from:'release'};
	if(CATID){
		obj.catId = CATID;
	}
	if(GOODSNAME){
		obj.goodsNameLike = GOODSNAME;
	}
	obj.page = CURRENT_PAGE;
	obj.rows = PAGE_COUNT;
	obj.goodsStatus = 72;
	$.post('/loadAuctionMicroGoods',obj,function(rsp){
		if(rsp.success){
			if(rsp.rows && rsp.rows.length > 0){
				$("#asgId").val(rsp.rows[0].id);
				makeAuctionGoodsDom(rsp.rows,true);
				CURRENT_PAGE ++;
			}
		}else{
			lh.alert(rsp.msg);
		}
	},'json');
}

function loadAuctionQuickGoods(id){
	var obj = {forAuction:1,from:'release'};
	if(CATID){
		obj.catId = CATID;
	}
	if(GOODSNAME){
		obj.goodsNameLike = GOODSNAME;
	}
	obj.auctionId = id;
	obj.page = CURRENT_PAGE;
	obj.rows = PAGE_COUNT;
	obj.goodsStatus = 73;
	$.post('/loadQuickAuctionGoods',obj,function(rsp){
		if(rsp.success){
			if(rsp.rows && rsp.rows.length > 0){
				makeAuctionGoodsDom(rsp.rows,true);
				CURRENT_PAGE ++;
			}
		}else{
			lh.alert(rsp.msg);
		}
	},'json');
}

function loadAuctionProfessionGoods(id){
	var obj = {forAuction:1,from:'release'};
	if(CATID){
		obj.catId = CATID;
	}
	if(GOODSNAME){
		obj.goodsNameLike = GOODSNAME;
	}
	obj.professionId = id;
	obj.page = CURRENT_PAGE;
	obj.rows = PAGE_COUNT;
	obj.goodsStatus = 71;
	$.post('/loadProfessionAuctionGoods',obj,function(rsp){
		if(rsp.success){
			if(rsp.rows && rsp.rows.length > 0){
				makeAuctionGoodsDom(rsp.rows,true);
				CURRENT_PAGE ++;
			}
		}else{
			lh.alert(rsp.msg);
		}
	},'json');
}

function makeAuctionGoodsDom(goodsList,isAppend,domId){
	if(!domId)domId = '#goodsList';
	TEMPLATE = $('#template1').html();
	Mustache.parse(TEMPLATE);   // optional, speeds up future uses
	var data = {
		rows:goodsList
    }
	var rendered = Mustache.render(TEMPLATE, data);
	$("#selectNum").text(goodsList.length);
	//GOODSLIST.push(rendered);
	if(isAppend){
		$(domId).append(rendered);
	}else{
		$(domId).html(rendered);
	}
	for(var a in goodsList){
		var goodsId = goodsList[a].goodsId;
		var priceBegin = goodsList[a].priceBegin;
		var increaseRangePrice = goodsList[a].increaseRangePrice;
		var goods = $("#img_"+goodsId);
		GOODSLIST.push(goods);
		$("#img_"+goodsId).remove();
		var ag = {goodsId:goodsId,priceBegin:priceBegin,shopPrice:priceBegin,id:goodsId,increaseRangePrice:increaseRangePrice};
		SELECTED_GOODS_ARY.push(ag);
	}
}


function showActionSheet(){
	var mask = $('#myMask');
	var weuiActionsheet = $('#weui_actionsheet');
	weuiActionsheet.addClass('weui_actionsheet_toggle');
	mask.show().addClass('weui_fade_toggle').click(function () {
		hideActionSheet(weuiActionsheet, mask);
	});
	$('#actionsheet_cancel1').click(function () {
		hideActionSheet(weuiActionsheet, mask);
	});
	weuiActionsheet.unbind('transitionend').unbind('webkitTransitionEnd');
}

function hideActionSheet(weuiActionsheet, mask) {
	weuiActionsheet.removeClass('weui_actionsheet_toggle');
	mask.removeClass('weui_fade_toggle');
	weuiActionsheet.on('transitionend', function () {
		mask.hide();
	}).on('webkitTransitionEnd', function () {
		mask.hide();
	})
}

function catValue(id,name,first){
	$("#scanSelected").show();
	$("#back").hide();
	if(first){
		showActionSheet();
	}else{
		var mask = $('#myMask');
		var weuiActionsheet = $('#weui_actionsheet');
		hideActionSheet(weuiActionsheet, mask);
	}
	$("#TypeName").text(name);
	$("#goodsList").empty();
	CATID = id;
	CURRENT_PAGE = 1;//切换后重新加载第一页
	loadGoods();
}

function loadGoods(){
	var obj = {forAuction:1,from:'release'};
	if(CATID){
		obj.catId = CATID;
	}
	if(GOODSNAME){
		obj.goodsNameLike = GOODSNAME;
	}
	obj.page = CURRENT_PAGE;
	obj.rows = PAGE_COUNT;
	$.post('/getMyGoodsList',obj,function(rsp){
		if(rsp.success){
			if(rsp.rows && rsp.rows.length > 0){
				makeGoodsDom(rsp.rows,true);
				CURRENT_PAGE ++;
			}
		}else{
			lh.alert(rsp.msg);
		}
	},'json');
}

function makeGoodsDom(goodsList,isAppend,domId){
	if(!domId)domId = '#goodsList';
	TEMPLATE = $('#template').html();
	Mustache.parse(TEMPLATE);   // optional, speeds up future uses
	var data = {
		rows:goodsList
    }
	var rendered = Mustache.render(TEMPLATE, data);
	if(GOODSLIST.length > 0){
		for(var i=0;i<GOODSLIST.length;i++){
			$(domId).append(GOODSLIST[i][0].outerHTML);
		}
	}
	if(isAppend){
		$(domId).append(rendered);
	}else{
		$(domId).html(rendered);
	}
}

function catGoods(){
	$("#scanSelected").hide();
	$("#back").show();
	$("#goodsList").empty();
	if(GOODSLIST.length > 0){
		for(var i=0;i<GOODSLIST.length;i++){
			$("#goodsList").append(GOODSLIST[i][0].outerHTML);
		}
	}else{
		var dom ='<li style="width: 100%;" class=" pointer" >'
			+'<div class="weui_cell_hd" style="text-align: center;margin-top:20px;">'
			+'<label class="myLabel" style="font-size:14px">暂无选中的藏品</label>'
			+'</div></li>';
		$("#goodsList").append(dom);
	}
}

function searchGoods(){
	var searchGoodsNames = $("#searchGoodsNames").val();
	$("#goodsList").empty();
	GOODSNAME = searchGoodsNames;
	CURRENT_PAGE = 1;//查询加载第一页数据
	loadGoods();
}

function showPriceBegin(goodsId,edit,priceBegin,increaseRangePrice){
	$("#goodsId").val(goodsId);
	$("#priceBegin").val('');
	$("#increaseRangePrice").val('');
	$("#priceTitle").text(PRICE_TITLE);
	$('#priceWin').show();
	if(edit == 'edit'){
		$("#priceSave").hide();
		$("#priceEdit").show();
	}else{
		$("#priceSave").show();
		$("#priceEdit").hide();
	}
	if(priceBegin){
		$("#priceBegin").val(priceBegin);
	}
	if(increaseRangePrice){
		$("#increaseRangePrice").val(increaseRangePrice);
	}
}

function doPriceBegin(operation){
	var goodsId = $("#goodsId").val();
	var priceBegin = $("#priceBegin").val();
	var increaseRangePrice = $("#increaseRangePrice").val();
	if(operation == 'cancel'){
		//removeGoods(goodsId);
		$('#priceWin').hide();
	}else if(operation == 'save'){
		if(!priceBegin){
			$("#tips").text('请输入价格').show();
			return;
		}
		if(!increaseRangePrice){
			$("#tips").text('请输入加价幅度').show();
			return;
		}
		checkGoodsBeforeSave(goodsId,priceBegin,increaseRangePrice);
		$("#priceBegin_"+goodsId).empty();
		var dom = '<div class="price_cp" style="color:red;">'+PRICE_TITLE+'为:'+priceBegin+'元</div>'
				+'<div class="price_cp" style="color:red;">&nbsp;加价幅度为:'+increaseRangePrice+'元</div>'
			+'<div><button class="weui_btn weui_btn_mini weui_btn_primary pointer fl" style="margin:2px;color: rgb(255, 255, 255);"  onclick="showPriceBegin('+goodsId+',\'edit\','+priceBegin+','+increaseRangePrice+')">修改价格</button></div>';
		$("#priceBegin_"+goodsId).append(dom).show();
		$('#priceWin').hide();
	}else if(operation == 'edit'){
		var idx = -1;
		for(var i=0;i<SELECTED_GOODS_ARY.length;i++){
			if(SELECTED_GOODS_ARY[i].goodsId == goodsId){
				idx = i;break;
			}
		}
		if(idx>=0)SELECTED_GOODS_ARY.splice(idx, 1);
		var ag = {goodsId:goodsId,priceBegin:priceBegin,shopPrice:priceBegin,id:goodsId,increaseRangePrice:increaseRangePrice};
		SELECTED_GOODS_ARY.push(ag);
		$("#priceBegin_"+goodsId).empty();
		var dom = '<div class="price_cp" style="color:red;">'+PRICE_TITLE+'为:'+priceBegin+'元</div>'
			+'<div class="price_cp" style="color:red;">&nbsp;加价幅度为:'+increaseRangePrice+'元</div>'
			+'<div><button class="weui_btn weui_btn_mini weui_btn_primary pointer fl" style="margin:2px;color: rgb(255, 255, 255);"  onclick="showPriceBegin('+goodsId+',\'edit\','+priceBegin+','+increaseRangePrice+')">修改价格</button></div>';
		$("#priceBegin_"+goodsId).append(dom).show();
		$('#priceWin').hide();
	}
}

function checkGoodsBeforeSave(goodsId,auctionPrice){
	var ag = {goodsId:goodsId,priceBegin:auctionPrice,shopPrice:auctionPrice,id:goodsId};
	SELECTED_GOODS_ARY.push(ag);
	$("#selectNum").text(SELECTED_GOODS_ARY.length);
	$("#add_"+goodsId).remove();
	var dom = '<button id="remove_'+goodsId+'" class="btn weui_btn_primary fl pointer" style="margin:2px;color: rgb(255, 255, 255);background-color: #920808;"  onclick="removeGoods('+goodsId+')">移除</button>';
	$(".price_cp_"+goodsId).append(dom);
	var goods = $("#img_"+goodsId);
	GOODSLIST.push(goods);
	//return true;
}

function removeGoods(goodsId){
	var idx = -1;
	for(var i=0;i<SELECTED_GOODS_ARY.length;i++){
		if(SELECTED_GOODS_ARY[i].goodsId == goodsId){
			idx = i;break;
		}
	}
	if(idx>=0)SELECTED_GOODS_ARY.splice(idx, 1);
	$("#selectNum").text(SELECTED_GOODS_ARY.length);
	$("#remove_"+goodsId).remove();
	var dom ='<button id="add_'+goodsId+'" class="btn weui_btn_primary fl pointer" style="margin:2px;color: rgb(255, 255, 255);"  onclick="showPriceBegin('+goodsId+')">添加</button>';
	$(".price_cp_"+goodsId).append(dom);
	var idx2 = -1;
	for(var i=0;i<GOODSLIST.length;i++){
		if(GOODSLIST[i].selector == "#img_"+goodsId){
			idx2 = i;break;
		}
	}
	if(idx2>=0)GOODSLIST.splice(idx2, 1);
	$("#priceBegin_"+goodsId).empty();
	//if(idx2>=0)$("#img_"+goodsId).remove();
}

function saveProfession(){
	if(SAVEING_FLAG)return;
	SAVEING_FLAG = true;
	var aiId = $("#aiId").val();
	var aqId = $("#aqId").val();
	var asgId = $("#asgId").val();
	var apId = localStorage.getItem("apId");
	var professionId = localStorage.getItem("professionId");
	var auctionQuickId = localStorage.getItem("auctionQuickId");
	var asId = localStorage.getItem("asId");
	//var aqId = localStorage.getItem("aqId");
	var comeFrom = localStorage.getItem("comeFrom");
	//var bounsNum = $('#bounsNum').val();
	//var bounsSinglePrice = $('#bounsSinglePrice').val();
	var bonusTypeId = localStorage.getItem("bonusTypeId");
	var bonus = localStorage.getItem("bonus");
	var bail = localStorage.getItem("bail");
	var startTime = localStorage.getItem("startTime");
	var day = localStorage.getItem("day");
	var auctionName = localStorage.getItem("auctionName");
	var typeId = localStorage.getItem("typeId");
	var b = [];//去除undefined后的结果
	for(var i=0;i<SELECTED_GOODS_ARY.length;i++){
	    if(typeof(SELECTED_GOODS_ARY[i].goodsId)!='undefined'){
	    	var ag = {goodsId:SELECTED_GOODS_ARY[i].goodsId,priceBegin:SELECTED_GOODS_ARY[i].priceBegin,id:SELECTED_GOODS_ARY[i].id,increaseRangePrice:SELECTED_GOODS_ARY[i].increaseRangePrice};
	        b.push(ag);
	    }
	}
	if(!b || b.length <= 0){
		lh.alert('请至少选择一件藏品');
		SAVEING_FLAG = false;
		return;
	}
	var gLength = b.length;
	if(gLength > 100){
		lh.alert('一次最多只能选择100件藏品');
		SAVEING_FLAG = false;
		return;
	}
	var goods = b;
	/*if(comeFrom == 3){
		if(gLength >= 2){
			lh.alert('微拍一次只能选择一件藏品进行拍卖');
			SAVEING_FLAG = false;
			return;
		}
		goods = b[0];
	}*/
	var param = {};
	if(day && day != 'undefined'){
		param.day = day;
	}
	//param.bounsNum = bounsNum;
	//param.bounsSinglePrice = bounsSinglePrice;
	if(bonusTypeId && bonusTypeId != 'undefined'){
		param.bonusTypeId = bonusTypeId;
	}
	if(bonus && bonus != 'undefined'){
		param.bonus = bonus;
	}
	if(bail && bail != 'undefined'){
		param.bail = bail;
	}
	if(startTime && startTime != 'undefined'){
		param.startTime = startTime;
	}
	if(auctionName && auctionName != 'undefined'){
		param.auctionName = auctionName;
	}
	if(comeFrom == 1){//专场
		param.id = professionId;
		param.instId = aiId;
		param.auctionGoodsAry = JSON.stringify(goods);
		TEMPDATA = param;
		addAuctionProfession();
		//$("#dialog").show();//TODO 如果有推广金额，要输入支付密码
	}else if(comeFrom == 2){//即时拍
		param.id = auctionQuickId;
		param.auctionQuickGoodsAry = JSON.stringify(goods);
		param.instId = aqId;
		param.typeId = typeId;
		addAuctionQuick(param);
	}else if(comeFrom == 3){//微拍
		var endTime = localStorage.getItem("endTime");
		//var param = {goodsId:goods.goodsId, priceBegin:goods.priceBegin,endTime:endTime};
		param.auctionMicroGoodsAry = JSON.stringify(goods);
		param.asId = "edit";
		param.endTime = endTime;
		//param.id = asgId;
		addAuctionMicro(param);
	}else if(comeFrom == 5) {//批发城
		param.GoodsAry = JSON.stringify(goods);
		addWholesaleGoods(param);
	}else{
		lh.jumpR('/goodsManageType');//无法识别，返回到选择发布类型页面
	}
}

function addAuctionQuick(param){
	frontBaseLoadingOpen();//加载遮罩
	$.post('/addOrUpdateAuctionQuick',param,function(rsp){
		SAVEING_FLAG = false;
		frontBaseLoadingClose();//解除遮罩
		frontLoginCheck(rsp);//登陆检查
		if(rsp.success){
			removeAuctionItems();
			lh.jumpR('/aqIndex');
		}else{
			if(rsp.code == 'jumpToMyShop'){
				frontBaseConfirm(rsp.msg, "lh.jumpR('/myShop')");
			}else{
				lh.alert(rsp.msg);
			}
		}
	},'json');
}

function addAuctionMicro(param){
	frontBaseLoadingOpen();//加载遮罩
	$.post('/addOrUpdateAs',param,function(rsp){
		SAVEING_FLAG = false;
		frontBaseLoadingClose();//解除遮罩
		frontLoginCheck(rsp);//登陆检查
		if(rsp.success){
			removeAuctionItems();
			lh.jumpR('/as');
		}else{
			lh.alert(rsp.msg);
		}
	},'json');
}

function addWholesaleGoods(param){
	frontBaseLoadingOpen();//加载遮罩
	$.post('/addWholesaleGoods',param,function(rsp){
		SAVEING_FLAG = false;
		frontBaseLoadingClose();//解除遮罩
		frontLoginCheck(rsp);//登陆检查
		if(rsp.success){
			removeAuctionItems();
			var userId = $("#userId").val();
			var url = '/ws/'+userId;
			lh.jumpR(url);
		}else{
			lh.alert(rsp.msg);
		}
	},'json');
}

function addAuctionProfession(){
	/*var payPassword = $("#payPassword").val();
	if(!payPassword){
		$("#tips").text('请输入支付密码').show();
		SAVEING_FLAG = false;
		return;
	}
	TEMPDATA.payPassword = payPassword;*/
	frontBaseLoadingOpen();//加载遮罩
	$.post('/addOrUpdateAuctionProfession',TEMPDATA,function(rsp){
		SAVEING_FLAG = false;
		frontBaseLoadingClose();//解除遮罩
		frontLoginCheck(rsp);//登陆检查
		if(rsp.success){
			removeAuctionItems();
			lh.jumpR('/inst');
		}else{
			if(rsp.code == 'jumpToMyShop'){
				frontBaseConfirm(rsp.msg, "lh.jumpR('/myShop')");
			}else{
				lh.alert(rsp.msg);
			}
		}
	},'json');
}

function removeAuctionItems(){
	localStorage.removeItem("apId");
	localStorage.removeItem("professionId");
	localStorage.removeItem("auctionQuickId");
	localStorage.removeItem("asId");
	localStorage.removeItem("aqId");
	localStorage.removeItem("comeFrom");
	localStorage.removeItem("bail");
	localStorage.removeItem("startTime");
	localStorage.removeItem("auctionName");
	localStorage.removeItem("typeId");
	localStorage.removeItem("day");
	localStorage.removeItem("bonusTypeId");
	localStorage.removeItem("bonus");
}

